/**
 * Created by L.jp
 * Description:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 *
 *
 * User: 86189
 * Date: 2023-03-17
 * Time: 2:23
 */
class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
public class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        /*ListNode head=new ListNode(-1);
        while ( list1!=null && list2 != null ){
            if(list1.val<= list2.val){
                head.next = list1;
                list1=list1.next;
            }else{
                head.next=list2;
                list2=list2.next;
            }
            head=head.next;
        }
        if(list1!=null){
            head.next = list1;
        }
        if(list2 != null){
            head.next=list2;
        }
        return head.next;*/
        
        //递归的解法，每一层的任务就是比较谁更小，然后新的节点的下一个节点就指向谁，之后再next
        //首先判空
        if(list1==null){
            return list2;
        }
        if ( list2==null ){
            return list1;
        }
        if(list1.val<= list2.val){
            //哪个小后面就接哪个
            list1.next=mergeTwoLists( list1.next,list2 );
            return list1;
        }else {
            list2.next=mergeTwoLists( list1.next,list2 );
            return list2;
        }
    }
}
